<?php

namespace app\common\model;

use think\Model;
class ReplyModel extends BaseReplyModel
{
    // protected $table_keyword = 'zbc_reply_content';
    protected $table="zbc_reply_content";
    // protected $autoWriteTimestamp = 'datetime';
    // // 定义时间戳字段名
    // protected $createTime = 'created';
    // protected $updateTime = 'updated';

    private $mediaImage_key="image";
    private $mediaAudio_key="audio";

    private $mediaImage_field="mediaImage";
    private $mediaAudio_field="mediaAudio";

    public function getKeywords($page=1,$size=10)
    {
        return $this->getReplys("keyword",['created'=>'desc'],"id,type,keyword,enabled",$page,$size);
    }

    public function getArticles($page=1,$size=10)
    {
        return $this->getReplys("article",['created'=>'desc'],null,$page,$size);
    }

    /**
     * 查询
     *
     * @param [type] $objectType 消息类型
     * @param [type] $order
     * @param [type] $field
     * @param integer $page
     * @param integer $size
     * @return void
     */
    public function getReplys($objectType=null,$order=null,$field=null,$page=1,$size=10)
    {
        $query=self::alias("reply")
            ->leftJoin("zbc_reply_asset asset","reply.imageAssetId = asset.id")
            ->where("reply.objectType",$objectType)
            ->field("reply.*,asset.path");

        $count=$query->count();    

        $query=self::table($query->buildSql())
            ->field($field)
            ->alias("reply")
            ->order($order)
            ->limit(($page-1)*$size,$size)
            ->buildSql();
        
        $query=self::table($query)->alias("reply");
        return ["data"=>$query->select(),"count"=>$count];
    }

    public function getReply($objectType=null,$id=null)
    {
        $query=self::alias("reply")
            ->leftJoin("zbc_reply_asset asset","reply.imageAssetId = asset.id")
            ->leftJoin("zbc_reply_article article","reply.newsId=article.id")
            ->leftJoin("zbc_reply_asset article_asset","article.imageAssetId=article_asset.id");

        if(!empty($objectType))
        {
            $query=$query->where("reply.objectType",$objectType);
        }

        if(!empty($id))
        {
            $query=$query->where("reply.id",$id);
        }

        $query=$query->field("reply.*,asset.path,article_asset.path articleImage,article.title articleTitle");

        return $query->find();
    }

    /**
     * 创建消息回复内容
     *
     * @param [type] $param
     * @param string $type keyword=>关键字 invalid=>无效关键字 focus=>关注
     * @return void
     */
    public function addReply($param,$type="keyword")
    {
        $isUpdate=true;
        
        if(!array_key_exists("id",$param)){
            $isUpdate=false;
        }

        if($isUpdate && empty($param["id"]))
        {
            unset($param["id"]);
            $isUpdate=false;
        }

        $this->handleMedia($param);

        $param["objectType"]=$type;
       
        return $this->addOrUpdate($param);
    }


    /**
     * 同个 type只能存在一条数据
     *
     * @param [type] $param
     * @param [type] $type
     * @return void
     */
    public function addOnlyReply($param,$type=null)
    {
        $isUpdate=true;

        if(!array_key_exists("id",$param)){
            $isUpdate=false;
        }

        if($isUpdate && empty($param["id"]))
        {
            unset($param["id"]);
            $isUpdate=false;
        }

        if(!$isUpdate){
            $item=self::where("objectType",$type)->find();
            if($item){
                $isUpdate=true;
                $param["id"]=$item->id; 
            }
        }

        $this->handleMedia($param);
        if(!$isUpdate) $param["objectType"]=$type;
        $result=$this->isUpdate($isUpdate)->save($param);
        return $result;
    }


    public function findReply($msg)
    {
        return $this->resolveReply($msg->Content,$msg->FromUserName,$msg->ToUserName);
    }

    public function findFocus($fromUser,$toUser)
    {
        $reply=self::where("enabled",1)
            ->where("objectType","focus")
            ->find();
        if(!$reply) return "";
        $resolver=new ReplyResolver;
        return $resolver->resolve($reply,$fromUser,$toUser);
    }

    public function resolveReply($keyword,$fromUser,$toUser)
    {
        $reply=self::where("enabled",1)
        ->where("objectType","keyword")
        ->where("keyword","like","%$keyword%")
        ->order("created","desc")
        ->find();

        if(!$reply)
        {
            $reply=self::where("enabled",1)
            ->where("objectType","invalid")
            ->find();
        }
        if(!$reply) return "";
        $resolver=new ReplyResolver;
        return $resolver->resolve($reply,$fromUser,$toUser);
    }

    private function addOrUpdate($param)
    {
        $isUpdate=true;
        if(!array_key_exists("id",$param)){
            $isUpdate=false;
        }

        $result=$this->isUpdate($isUpdate)->save($param);
        $result=$this->id;
        return $result;
    }

    /**
     * 处理回复消息 中的 上传文件
     *
     * @param [type] $param
     * @return void
     */
    private function handleMedia(&$param)
    {
        $fileName="";
        $type="";
        $typeId="";

        //获取消息类型 text image music
        if(array_key_exists("type",$param))
        {
            $type=$param["type"];
        }

        switch($type)
        {
            case "image"://图片消息
                if(array_key_exists($this->mediaImage_key,$param))
                {
                    $fileName=$param[$this->mediaImage_key];
                }
                $typeId=$this->mediaImage_field;
            break;
            case "voice"://声音消息
                if(array_key_exists($this->mediaAudio_key,$param))
                {
                    $fileName=$param[$this->mediaAudio_key];
                }
                $typeId=$this->mediaAudio_field;
            break;
        }

        if(array_key_exists($this->mediaAudio_key,$param)){
            unset($param[$this->mediaAudio_key]);
        }

        if(array_key_exists($this->mediaImage_key,$param)){
            unset($param[$this->mediaImage_key]);
        }

        //有文件但是没有 ID 的情况 被 认为 是新的文件 需要传到微信上去
        if(!empty($fileName) && empty($param[$typeId]))
        {
            $file=$_SERVER["DOCUMENT_ROOT"] .$fileName;
            if(file_exists($file)){
                // $config = \config("wechat.");
                // $media=new \WeChat\Media($config);
                $upImage=$this->getMedia()->addMaterial($file);
                $param[$typeId]=$upImage["media_id"];
            }
        }
    }

}

class ReplyResolver
{
    public function resolve($reply,$fromUser,$toUser)
    {
        if(empty($reply)) return "";

        try
        {
            $config = \config("wechat.");
            $api=new \WeChat\Receive($config);
            switch($reply->type)
            {
                case "text":
                    return $api->text($reply->content)->reply();
                case "image":
                    return $api->image($reply->mediaImage)->reply();
                case "news":
                    $article=new ReplyArticleModel;
                    $content=$article->findReplyArticle($reply->newsId);
                    return is_null($content)?"":$api->news($content)->reply();
                case "voice":
                    return $api->voice($reply->mediaAudio)->reply();
            }
        }
        catch(\Exception $ex)
        {

        }
        
        return "";
    }
}

